package hotel.quartz.oversea.job.switchs;


import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import hotel.base.oversea.constant.CommonConstants;
import hotel.base.oversea.constant.CommonUrlConstants;
import hotel.base.oversea.constant.SwitchConstants;
import hotel.base.oversea.constant.enums.MessageEnums;
import hotel.base.oversea.constant.quartz.UrlSwitchsEnums;
import hotel.base.oversea.utils.JacksonUtil;
import hotel.base.oversea.utils.Result;
import hotel.base.oversea.utils.SendUtils;
import hotel.quartz.oversea.config.service.RedisService;
import hotel.quartz.oversea.job.base.BaseJob;
import hotel.quartz.oversea.service.JobAndTriggerService;
import hotel.quartz.oversea.util.JobRestTemplateUtils;
import hotel.quartz.oversea.vo.dto.switchs.SwitchCreateRoomJobDto;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 携程创建售卖房型定时器
 *
 * @author HuangT
 * @date 2020/7/14 14:27
 */
@Slf4j
public class SwitchCreateRoomJob implements BaseJob {
    private String jobGroupName = SwitchConstants.JOB_GROUP_NAME_SWITCHS;
    private String jobClassName = this.getClass().getName();
    @Autowired
    private JobAndTriggerService jobAndTriggerService;

    private final String timestamp = "scrj" + System.currentTimeMillis();
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RedisService redisService;


    /**
     * 每次创建一个售卖房型  6-8秒调用 接口限制
     * 根据 switch_create_basic_room表获取需创建销售房型的房型数据，创建成功后需更新create_state状态
     *
     * @date 2020/7/14 14:40
     */
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        log.info("Switch Create Room Job {} >>>>>>>> 携程创建售卖房型开始时间: {}", timestamp, DateUtil.now());

        String thisHourStr = null;
        String notTodoAtTimeHour = null;
        if(null != redisService.get("mtsw_job_price_not_todo_at_time")){//value="23,00,01"
            notTodoAtTimeHour = (String)redisService.get("mtsw_job_price_not_todo_at_time");
            thisHourStr = hotel.base.oversea.utils.DateUtil.formatDate(new Date(),"HH");
        }
        if(!ObjectUtils.isEmpty(notTodoAtTimeHour) && notTodoAtTimeHour.contains(thisHourStr)){
            if(null == redisService.get("mtsw_send_not_todo_price")){
                SendUtils.dingMsgNotLog("[SW-JOB-PRICE-AT-TIME]指定时间段不执行-创建售卖房型定时器",hotel.base.oversea.utils.DateUtil.getCurrTime()+" notTodoAtTimeHour="+notTodoAtTimeHour, MessageEnums.genre.GOODS_STATUS_AND_PRICE.getCode(),restTemplate);
                redisService.setUnit("mtsw_send_not_todo_price",1,2L, TimeUnit.HOURS);
            }
            return;
        }
//        if (StringUtils.isEmpty(accessToken)) {
//            log.error("Switch Create Room Job {} error accessToken null", timestamp);
//            return;
//        }
        //查询 switch_create_basic_room 表获取房型数据  /switchCreateBasicRoom/getBasicRoomInfoForJob
        /*String getBasicRoomInfoForJobUrl = CommonUrlConstants.SWITCHS_HOST + UrlSwitchsEnums.switchCreateRoomJob.POST_SWITCH_BASIC_ROOM_INFO.getValue();*/
        String getBasicRoomInfoForJobUrl = CommonUrlConstants.SWITCHS_ONLINE_HOST + UrlSwitchsEnums.switchCreateRoomJob.POST_SWITCH_BASIC_ROOM_INFO.getValue();
        Result result = getBasicRoomInfoForJob(getBasicRoomInfoForJobUrl);//获取数据时 对create_state update为 1
        if (null != result && result.getCode()== CommonConstants.SUCCESS && null != result.getData()) {
            SwitchCreateRoomJobDto switchCreateRoomJobDto = JacksonUtil.objToBean(result.getData(), SwitchCreateRoomJobDto.class);
            log.info("Switch Create Room Job {} 携程创建售卖房型 获取到子物理房型信息: {}", timestamp, JSON.toJSONString(switchCreateRoomJobDto));
            if(switchCreateRoomJobDto != null) {
                //请求创建售卖房型接口 switchCreateRoom/createRoom
                String createRoomUrl = CommonUrlConstants.SWITCHS_ONLINE_HOST + UrlSwitchsEnums.switchCreateRoomJob.POST_SWITCH_CREATE_ROOM.getValue();//+ "?access_token=" + accessToken;
                Result responseCreate = createRoom(createRoomUrl, switchCreateRoomJobDto);
                String updateBasicRoomInfoForJobUrl = CommonUrlConstants.SWITCHS_HOST + UrlSwitchsEnums.switchCreateRoomJob.POST_SWITCH_UPDATE_BASIC_ROOM_INFO.getValue();//+ "?access_token=" + accessToken;
                if(responseCreate.getCode()!= CommonConstants.SUCCESS){
                    log.error("Switch Create Room Job {} 携程创建售卖房型 获取到子物理房型信息: {},{}", timestamp, JSON.toJSONString(responseCreate), JSON.toJSONString(switchCreateRoomJobDto));
                    if(null != responseCreate.getMsg() && responseCreate.getMsg().toString().contains("接口认证失败")
                         /*   || responseCreate.getCode() == -1
                            || responseCreate.getCode() == 1002
                            || responseCreate.getCode() == 1003
                            || responseCreate.getCode() == 1004*/
                            /*|| responseCreate.getCode() == 1005*/){
                        //创建房型异常，状态还原为0
                        switchCreateRoomJobDto.setCreateState(0);
                        updateBasicRoomInfoForJob(updateBasicRoomInfoForJobUrl, switchCreateRoomJobDto, hotel.base.oversea.utils.DateUtil.getCurrTime()+" "+ JSON.toJSONString(responseCreate));
                    }else{
                        //该子物理房型，不符合创建售卖房型，状态改为失败2
                        switchCreateRoomJobDto.setCreateState(2);
                        updateBasicRoomInfoForJob(updateBasicRoomInfoForJobUrl, switchCreateRoomJobDto, hotel.base.oversea.utils.DateUtil.getCurrTime()+" "+ JSON.toJSONString(responseCreate));
                    }
                }else{
                    switchCreateRoomJobDto.setCreateState(1);
                    updateBasicRoomInfoForJob(updateBasicRoomInfoForJobUrl, switchCreateRoomJobDto, hotel.base.oversea.utils.DateUtil.getCurrTime()+" 当前为真实创建成功"+ JSON.toJSONString(responseCreate));
                }

            }
        }else{
            log.info("Switch Create Room Job {} >>>>>>>> 当前无获取到可执行的需创建售卖房型的 子物理房型信息 switch_create_basic_room，程序暂停！！！: {}，{}", timestamp, DateUtil.now(), JSON.toJSONString(result));
            //endingJob();
            //log.info("Switch Create Room Job {} >>>>>>>> 当前无获取到可执行的需创建售卖房型的 子物理房型信息 switch_create_basic_room，程序继续不停跑: {}，{}", timestamp, DateUtil.now(),JSON.toJSONString(result));
        }
        log.info("Switch Create Room Job {} >>>>>>>> 携程创建售卖房型结束时间: {}", timestamp, DateUtil.now());
    }

    /**
     * 无数据 结束定时器
     */
    public void endingJob(){
        //redis标识，标识存在了创建售卖房型，推送价格时候


        //已最后一页，暂停定时器,删除rediskey
        /*JobForm jobForm = new JobForm();  version 2020-08-24  调整为不暂停一直跑  配合创建子物理房型定时器不停跑
        jobForm.setJobClassName(jobClassName);
        jobForm.setJobGroupName(jobGroupName);
        try {
            jobAndTriggerService.pauseJob(jobForm);
            log.warn("Switch Create Room Job {} 携程创建售卖房型执行暂停！: {},{}",timestamp,jobGroupName,jobClassName);
        } catch (SchedulerException e) {
            log.error(e.getMessage(),e);
        }*/
    }

    /**
     * <H1>更新售卖房型状态</H1>
     *
     * @param updateBasicRoomInfoForJobUrl
     * @param switchCreateRoomJobDto
     * @return void
     * @author HuangT
     * @date 2020/7/14 16:00
    */
    private void updateBasicRoomInfoForJob(String updateBasicRoomInfoForJobUrl, SwitchCreateRoomJobDto switchCreateRoomJobDto, String remark) {
        log.info("Switch Create Room Job {} >>>>>>>> 携程创建售卖房型 进入updateBasicRoomInfoForJob: {}", timestamp, JSON.toJSONString(switchCreateRoomJobDto));
        //请求参数
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("id", switchCreateRoomJobDto.getId());
        dataMap.put("createState", switchCreateRoomJobDto.getCreateState());
        dataMap.put("createStateRemark", remark);
        String dataJson = JacksonUtil.objectToJson(dataMap);
        //发起请求
        Result response = JobRestTemplateUtils.post(updateBasicRoomInfoForJobUrl,dataJson,restTemplate);
        if(response.getCode()!= CommonConstants.SUCCESS){
            log.info("Switch Create Room Job {} >>>>>>>> 携程创建售卖房型 updateBasicRoomInfoForJob 更新返回: {}", timestamp, JSON.toJSONString(response));
        }
    }

    /**
     * <H1>请求创建售卖房型接口 switchCreateRoom/createRoom</H1>
     *
     * @param createRoomUrl
     * @param switchCreateRoomJobDto
     * @return hotel.base.oversea.utils.Result
     * @author HuangT
     * @date 2020/7/14 15:29
    */
    private Result createRoom(String createRoomUrl, SwitchCreateRoomJobDto switchCreateRoomJobDto) {
        log.info("Switch Create Room Job {} >>>>>>>> 携程创建售卖房型 进入 createRoom: {}", timestamp, JSON.toJSONString(switchCreateRoomJobDto));
        //请求参数
        Map<String, Object> dataMap = new HashMap<>();
        //子酒店ID
        dataMap.put("hotelId", switchCreateRoomJobDto.getChildHotelId());
        //子物理房型ID
        dataMap.put("basicRoomTypeId", switchCreateRoomJobDto.getBasicRoomId());
        String dataJson = JacksonUtil.objectToJson(dataMap);
        //发起请求
        Result response = JobRestTemplateUtils.post(createRoomUrl,dataJson,restTemplate);
        if(response.getCode()!= CommonConstants.SUCCESS){
            log.error("Switch Create Room Job {} 获取子酒店ID和子物理房型ID createRoom 发起请求返回失败", JSON.toJSONString(response));
        }
        return response;
    }

    /**
     * <H1>请求子物理房型表，获取子酒店ID和子物理房型ID </H1>
     *
     * @param getBasicRoomInfoForJobUrl
     * @return hotel.base.oversea.utils.Result
     * @author HuangT
     * @date 2020/7/14 15:13
     */
    private Result getBasicRoomInfoForJob(String getBasicRoomInfoForJobUrl) {
        Map map = new HashMap();
//        map.put("access_token",accessToken);
        //发起请求
        Result response = JobRestTemplateUtils.get(getBasicRoomInfoForJobUrl,map,restTemplate);
        if(response.getCode()!= CommonConstants.SUCCESS){
            log.error("Switch Create Room Job {} 获取子酒店ID和子物理房型ID getBasicRoomInfoForJob 发起请求返回失败: {}",timestamp, JSON.toJSONString(response));
        }
        return response;
    }


}
